from fastapi import FastAPI,Response
import uvicorn
import os
from pydantic import BaseModel
import json

#创建折线图
def create_line_chart(indata: dict):
    #字典示例
    # {
    #     "title": "生产图表", #表的标题
    #     "yname": "生产量", #y轴名称
    #     "lname": "产水量,产气量", #线的名称
    #     "data" : "100,122,123;105,111,132", #数据
    #     "x_axis" : "2025年4月1日,2025年4月2日,2025年4月3日" #x轴数据
    # }

    #解析字典中的参数
    title = indata["title"]
    yname = indata["yname"]
    lname = indata["lname"].split(",")
    tmp = indata["data"].split(";")
    try:
        data = [[float(y) if y != "" else None for y in x.split(",")] for x in tmp]
    except:
        return "生成图表错误，可能是用于生成表格的数据不存在或者有误"
    x_axis = indata["x_axis"].split(",")
    print(data)
    print(x_axis)

    #检查数据x轴是否存在数据
    if len(x_axis) == 1 and x_axis[0] == "":
        return "用于生成图表的数据不存在"

    #确定y轴的最大值和最小值
    try:
        y_min = float('inf')
        y_max = float('-inf')
        for x in data:
            for y in x:
                if y is not None:
                    y_min = min(y_min, y)
                    y_max = max(y_max, y)
        print(y_min,y_max)
        if y_min == float('inf'):
            y_min = y_max = 10
        y_min = int(y_min - y_min / 10) - 2
        y_max = int(y_max + y_max / 10) + 2
    except Exception as e:
        return "生成图表错误，可能是用于生成表格的数据不存在或者有误"

    #创建完整的ECharts配置
    echarts_config = {
        'title': {
            'text': title
        },
        'tooltip': {
            'trigger': 'axis'
        },
        'legend': {
            'data': lname
        },
        'xAxis': {
            'type': 'category',
            'data': x_axis
        },
        'yAxis': {
            'type': 'value',
            'min': y_min,
            'max': y_max,
            'name': yname
        },
        'series': [],
        "toolbox": {  # 添加工具箱配置
            "feature": {
                "magicType": {
                    "type": ['line', 'bar'],  # 支持的图表类型
                    "title": {
                        "line": "折线图",
                        "bar": "柱状图",
                    }
                }
            }
        }

    }
    for i in range(0,len(data)):
        tmp = {
            'name': lname[i],
            'type': 'line',
            'data': data[i],
            'symbol': 'none'
        }
        echarts_config['series'].append(tmp)
    output = "```echarts\n" + json.dumps(echarts_config, indent=2, ensure_ascii=False) + "\n```"
    return output

#创建饼图
def create_pie_chart(indata: dict):
    # 字典示例
    # {
    #     "title": "销售占比", #表的标题
    #     "name": "服饰,数码,家居,食品,图书,体育", #表中每个数据的名称
    #     "value": "335,310,234,135,1548,500" #表中的数据
    # }

    #参数是否为空
    if len(indata["title"]) == 0 or len(indata["name"]) == 0 or len(indata["value"]) == 0:
        return "存在参数为空"

    #解析字典中的参数
    title = indata["title"]
    name = indata["name"].split(",")
    tmp = indata["value"].split(",")
    value = [float(x) for x in tmp]

    #检查参数完整性
    if len(name) != len(value):
        return "name,value数量不匹配"

    #创建完整的ECharts配置
    echarts_config = {
        "title": {
            "text": title,
            "left": "center"
        },
        "tooltip": {
            "trigger": "item",
            "formatter": "{a} <br/>{b}: {c} ({d}%)"
        },
        # "legend": {
        #     "orient": "vertical",
        #     "left": "left",
        #     "data": ["服饰", "数码", "家居", "食品", "图书","体育"]
        # },
        "series": [{
            "name": "销售占比",
            "type": "pie",
            "radius": "50%",
            "data": [],
            "emphasis": {
                "itemStyle": {
                    "shadowBlur": 10,
                    "shadowOffsetX": 0,
                    "shadowColor": "rgba(0, 0, 0, 0.5)"
                }
            },
            "label": {
                "show": True,
                "formatter": "{b}: {d}%",
                "color": "#333"
            },
            "avoidLabelOverlap": True
        }]
    }
    for i in range(0,len(name)):
        tmp = {
            "value": value[i],
            "name": name[i]
        }
        echarts_config["series"][0]["data"].append(tmp)
    output = "```echarts\n" + json.dumps(echarts_config, indent=2, ensure_ascii=False) + "\n```"
    return output


#创建折线图需要传入的参数
class line_chart_data(BaseModel):
    title: str #表的标题
    yname: str #y轴名称
    lname: str #线的名称
    data: str #数据
    x_axis: str #x轴数据
#创建饼图需要传入的参数
class pie_chart_data(BaseModel):
    title: str #表的标题
    name: str #表中每个数据的名称
    value: str #表中的数据

def main():
    app = FastAPI()

    @app.get("/line_chart")
    async def handle_line_chart(data: line_chart_data):
        data_dict = data.dict()
        res = create_line_chart(data_dict)
        return Response(content=res, media_type="text/plain")

    @app.get("/pie_chart")
    async def handle_pie_chart(data: pie_chart_data):
        data_dict = data.dict()
        res = create_pie_chart(data_dict)
        return Response(content=res, media_type="text/plain")
    

    return app

if __name__ == "__main__":
    app = main()
    api_host = os.environ.get("API_HOST", "0.0.0.0")
    api_port = int(os.environ.get("API_PORT", "8113"))
    uvicorn.run(app, host=api_host, port=api_port, log_config={
            "version": 1,
            "formatters": {
                "default": {
                    "()": "uvicorn.logging.DefaultFormatter",
                    "fmt": "%(asctime)s - %(levelprefix)s %(message)s",
                    "datefmt": "%Y-%m-%d %H:%M:%S",
                },
            },
            "handlers": {
                "default": {
                    "formatter": "default",
                    "class": "logging.StreamHandler",
                    "stream": "ext://sys.stderr",
                },
            },
            "loggers": {
                "uvicorn": {"handlers": ["default"], "level": "INFO"},
            },
        })
